package chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ChatThread extends Thread
{
	Socket socket;
	BufferedReader reader;
	PrintWriter writer;
	ChatThread(Socket socket)
	{
		this.socket=socket;
	}
	public void run()
	{	
		SocketManager manager=new SocketManager();
		try
		{				
			reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
			writer=new PrintWriter(socket.getOutputStream(),true);
			String message;
			while((message=reader.readLine())!=null)
			{
				System.out.println(message);
				manager.sendMessage(message);
			}
		}
		catch(Exception e)
		{
		   System.err.println("发生异常:"+e);
		   e.printStackTrace();
		}
		finally
		{
			try
			{	
				manager.remove(socket);
				if(reader!=null)
					reader.close();
				if(writer!=null)
				writer.close();
				if(socket!=null)
				socket.close();
				reader=null;
				writer=null;
				socket=null;
				System.out.println("用户下线");
				manager.sendClientNum();
		
			}
			catch(Exception e)
			{
			    System.err.println("发生异常:"+e);
		        e.printStackTrace();
			}
		}
	}
}
